/**
 * 
 */
package partitioner;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author puneet
 * 
 */
public class PartitionDAODatabaseImpl implements PartitionDAO {

	public Connection dbConn;
	public PartitionDAODatabaseImpl(Connection conn) {
		this.dbConn = conn;
	}
	public Connection getDbConn() {
		return dbConn;
	}
	
	private boolean debug = false;
	public boolean isDebug() {
		return debug;
	}
	public void setDebug(boolean debug) {
		this.debug = debug;
	}
	public void setDbConn(Connection dbConn) {
		this.dbConn = dbConn;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see partitioner.PartitionDAO#getNeighbors(java.lang.String)
	 */
	@Override
	public List<String> getNeighbors(String node) throws NodeNotFoundException,
			DataAccessException {
		try {
			if(debug) {
				System.out.println("Getting data for node: "+node);
			}
			PreparedStatement pst = dbConn.prepareStatement("select node,neighbors from nodestable where node=?");
			pst.setString(1, node.trim());
			ResultSet rs = pst.executeQuery();
			
			if (rs.next()) {
				List<String> returnList = Arrays.asList(rs.getString("neighbors").split("\\s"));
				rs.close();
				return returnList;
			}else {
				System.out.println("rs.next() is null for node"+node+"length:"+node.length()+" "+node.getClass());
			}
		} catch (Exception e) {
			throw new DataAccessException(e);
		}
		return null;
	}

	@Override
	public Map<String, List<String>> getNeighborsForAllNodes(List<String> nodes)
			throws NodeNotFoundException, DataAccessException {
		Map<String, List<String>> nodeNeighborMap = new HashMap<String, List<String>>();
		for (String node : nodes) {
			try {
				List<String> neighbors = getNeighbors(node);
				nodeNeighborMap.put(node, neighbors);
			} catch (Exception e) {
				nodeNeighborMap.put(node, null);
			}
		}
		return nodeNeighborMap;
	}


	@Override
	public boolean containsNode(String node) throws DataAccessException {
		try {
			PreparedStatement pst = dbConn.prepareStatement("select count(1) from nodestable where node=?");
			pst.setString(1, node);
			ResultSet rs = pst.executeQuery();
			if(rs.next()) {
				if(rs.getInt(1) > 0) {
					return true;
				}
			}
			return false;
		}catch(Exception e) {
			throw new DataAccessException(e);
		}
	}

}
